package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;

import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

    }

    @Override
    public List<ProductVo> allProduct() {
//        String product = redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        //从redis中获取数据
        String json = redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if(json != null) {
            return JSONUtil.toList(json, ProductVo.class);
        }
        return null;
    }

    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        // 1.设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if(count > 0) {
            throw new BaseException("设备名称重复");
        }

        // 2.设备标识是否重复
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if(count > 0) {
            throw new BaseException("设备标识码重复");
        }
       //
        // 3判断同一位置是否绑定了相同的产品
//        count = count(Wrappers.<Device>lambdaQuery()
//                .eq(Device::getProductKey, dto.getProductKey())
//                .eq(Device::getBindingLocation, dto.getBindingLocation())
//                .eq(Device::getLocationType, dto.getLocationType())
//                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
//
        count =this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation,dto.getBindingLocation())
                .eq(Device::getLocationType,dto.getLocationType())
                .eq(Device::getProductKey,dto.getProductKey())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())

       );
        if(count > 0) {
            throw new BaseException("同一位置绑定了相同产品");
        }

        // IoT平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());

        // 秘钥设置
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);

        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201){
            throw new BaseException("注册设备失败");
        }

        //保存设备信息到本地数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setBindingLocation(String.valueOf(dto.getBindingLocation()));
        device.setIotId(response.getDeviceId());
        this.save(device);
    }
//查询设备详情
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //3.查询本地数据库
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            throw new BaseException("设备不存在");
        }

        //2.查询物联网平台IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备详情失败");
        }
        String status = response.getStatus();
        String activeTimeStr = response.getActiveTime();


        //1.封装数据
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        vo.setDeviceStatus(status);
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = DateTimeZoneConverter.utcToShanghai(activeTime);
            vo.setActiveTime(activeTime);
        }

        return vo;
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询设备影子数据失败");
        }
        //1.1
        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollectionUtil.isEmpty(shadowList)){
            return Collections.emptyList();
        }
        //1.2
        DeviceShadowProperties deviceShadowProperties = shadowList.get(0).getReported();
        //1.3
        Object properties2 = deviceShadowProperties.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties2);
        //1.4
        String eventTimeStr = deviceShadowProperties.getEventTime();
//        把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

//        final LocalDateTime time =DateTimeZoneConverter.utcToShanghai(activeTime);

        //2
        List<Map<String, Object>> list = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }


}
